"""
main_window

Author: {{ cookiecutter.full_name }}
Date: 

All processing to be done in threads using signal/slot

"""

import sys,os,logging
import time
from functools import partial

from PyQt5.QtCore import Qt, QSize, QPoint, QByteArray, QProcess, QThread, QFile, QTextStream
from PyQt5.QtGui import QIcon, QPixmap, QMovie
from PyQt5.QtWidgets import (QAction, QApplication, QDesktopWidget, QDialog, QFileDialog,
                             QHBoxLayout, QLabel, QMainWindow, QToolBar, QVBoxLayout, QWidget, QSplashScreen,
                             QStyleFactory)

import resources_rc
from libs.constants import *
from libs.settings import Settings
from libs.utils import newAction, struct, addActions
from ui.dialogs import AboutDialog
from ui.main_widget import MainWidget
from ui.startloading import loading
from worker.example_receiverThread import ReceiverThread

__appname__ = ''
__version__ = '0.0.1'


class MainWindow(QMainWindow):
    """Create the main window that stores all of the widgets necessary for the application."""

    def __init__(self, parent=None):
        """Initialize the components of the main window."""
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('MainWindow')
        self.setWindowIcon(QIcon(':/ic_insert_drive_file_black.png'))

        ## start loading screen
        self.loading = loading(self)
        self.loading.loadingclosed.connect(self.close)
        self.loading.show()


        #get last windows settings
        self.settings = Settings('{{cookiecutter.application_name}}')
        self.settings.load()
        settings = self.settings
        size = settings.get(SETTING_WIN_SIZE, QSize(800, 600))
        position = QPoint(0, 0)
        saved_position = settings.get(SETTING_WIN_POSE, position)
        # Fix the multiple monitors issue
        for i in range(QApplication.desktop().screenCount()):
            if QApplication.desktop().availableGeometry(i).contains(saved_position):
                position = saved_position
                break
        self.restoreState(settings.get(SETTING_WIN_STATE, QByteArray()))
        self.resize(size)
        self.move(position)

        #setup central widget
        self.widget = MainWidget(self)
        self.setCentralWidget(self.widget)


        
        {% if cookiecutter.insert_menubar_toolbar == 'yes' -%}
        #other widget,like dialog DockWidget
        self.about_dialog = AboutDialog()

        #init_actions
        self.init_actions()

        # init menu
        self.menu_bar = self.menuBar()
        self.file_menu()
        self.help_menu()
        
        # tool bar example
        self.tool_bar_items()
        {%- endif %}
        


        {% if cookiecutter.insert_statusbar == 'yes' -%}
        self.status_bar = self.statusBar()
        self.status('Ready', 5000)
        {%- endif %}
        
        #init status bar


        {% if cookiecutter.use_dark_style == 'yes' -%}
        # todo qss example
        # https://github.com/ColinDuquesnoy/QDarkStyleSheet
        f = QFile(":qss/qdarkstyle_style")
        if not f.exists():
            logging.error("Unable to load stylesheet, file not found in "
                            "resources")
        else:
            f.open(QFile.ReadOnly | QFile.Text)
            ts = QTextStream(f)
            qssStyle = ts.readAll()
            f.close()
            self.setStyleSheet(qssStyle)
        {%- endif %}
        
        {% if cookiecutter.example_qthread == 'yes' -%}
        # threading sigel/slot exmaple
        self.init_workers()
        {%- endif %}

        #time.sleep(0.5)
        self.loading.close()
        
        
    {% if cookiecutter.insert_menubar_toolbar == 'yes' -%}
    def init_actions(self):
        # Actions
        open = newAction(self, 'Open File', self.open_file,'Ctrl+O', 'ic_open_in_new_black.png', 'Open a file into MainWindow')
        quit = newAction(self, 'Exit', QApplication.quit,'Ctrl+Q', 'quit.png', 'Exit Application')
        resetAll = newAction(self, 'Rest Setting', self.resetAll, None, 'resetall.png', 'resetAllDetail')
        about = newAction(self, 'About', self.about_dialog.exec_, 'CTRL+H', None, 'About the application.')

        # Store actions for further handling.
        self.actions = struct(open=open, quit=quit, resetAll=resetAll,about=about)


    def file_menu(self):
        """Create a file submenu with an Open File item that opens a file dialog."""
        self.file_sub_menu = self.menu_bar.addMenu('File')
        addActions(self.file_sub_menu ,(self.actions.open,self.actions.quit,self.actions.resetAll))


    def help_menu(self):
        """Create a help submenu with an About item tha opens an about dialog."""
        self.help_sub_menu = self.menu_bar.addMenu('Help')

        self.help_sub_menu.addAction(self.actions.about)

    def tool_bar_items(self):
        """Create a tool bar for the main window."""
        self.tool_bar = QToolBar('tools')
        self.tool_bar.setObjectName('title ToolBar' )
        self.addToolBar(Qt.TopToolBarArea, self.tool_bar)

        #self.tool_bar.setOrientation(Qt.Vertical)
        #self.tool_bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.tool_bar.setMovable(False)

        self.tool_bar.addAction(self.actions.open)

    def open_file(self):
        """Open a QFileDialog to allow the user to open a file into the application."""
        filename, accepted = QFileDialog.getOpenFileName(self, 'Open File') #(self, '%s - Choose Image or Label file' % __appname__, path, filters)

        if accepted and filename:
            with open(filename) as file:
                file.read()
    {%- endif %}
    
    
    {% if cookiecutter.example_qthread == 'yes' -%}
    def init_workers(self):
        self.thread_Receiver = ReceiverThread(self)
        {% if cookiecutter.insert_statusbar == 'yes' -%}
        self.thread_Receiver.sig_newReceive.connect(self.status)
        {%- endif %}
        
        self.thread_Receiver.start(QThread.NormalPriority)
        logging.info('Thread start : Receiver ')
    {%- endif %}
        
    {% if cookiecutter.insert_statusbar == 'yes' -%}    
    def status(self, msg, delay=5000,error=False):
        # display message and apply stylesheet based on message type
        if error:
            self.status_bar.setStyleSheet(
                "QStatusBar{padding-left:8px;color:red;font-weight:bold;}")
        else:
            self.status_bar.setStyleSheet(
                "QStatusBar{padding-left:8px;color:black;font-weight;}")

        self.status_bar.showMessage(msg,delay)
    {%- endif %}
    
    def resetAll(self):
        self.settings.reset()
        self.close()
        proc = QProcess()
        proc.startDetached(os.path.abspath(__file__))

    def closeEvent(self, event):
        #if not self.mayContinue():
        #    event.ignore()
        settings = self.settings

        settings[SETTING_WIN_SIZE] = self.size()
        settings[SETTING_WIN_POSE] = self.pos()
        settings[SETTING_WIN_STATE] = self.saveState()

        settings.save()

def main(argv=[]):
    app = QApplication(argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(QIcon(':/app.png'))

    window = MainWindow()
    #desktop = QDesktopWidget().availableGeometry()
    #width = (desktop.width() - window.width()) / 2
    #height = (desktop.height() - window.height()) / 2
    #window.move(width, height)


    window.show()

    sys.exit(app.exec_())
    
if __name__ == "__main__":
    main(sys.argv)
